<template>
    <!-- 作业管理-工作计划 -->
    <div class="empReward">
        <div class="top">
            <div class="search">
                <div class="list">
                    <!-- <DatePicker
                        type="daterange"
                        :clearable="false"
                        placeholder="开始时间   -   结束时间"
                        style="width: 200px"
                        v-model="value"
                        @on-change="getTime"
                    ></DatePicker> -->
                    <el-date-picker
                        v-model="value"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        @change="getTime"
                        :clearable="false"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </div>
                <!-- <div class="list">
                    <Input placeholder="人员姓名搜索" style="width:150px" v-model="keyword" clearable />
                    <input type="password" autocomplete="new-password" style="display: none" />
                </div> -->
                <div class="list" @click="onSerch">
                    <Button type="primary">搜索</Button>
                </div>
                <div class="list" @click="onReset">
                    <Button>重置</Button>
                </div>
            </div>
            <div class="down">
                <el-button type="primary" @click="updateRow(0)" size="small" plain>添加工作计划</el-button>
            </div>
        </div>
        <div class="bottom">
            <div class="table">
                <el-table :data="list" :height="tableHeight" :stripe="true" style="width: 100%" >
                    <el-table-column prop="planName" label="计划名称" width="150"></el-table-column>
                    <el-table-column prop="workContent" label="工作内容" width="200"></el-table-column>
                    <el-table-column prop="risk" label="危险点" width="200"></el-table-column>
                    <el-table-column prop="measures" label="措施内容" width="600"></el-table-column>
                    <el-table-column prop="workArea.name" label="所属区域" width="150"></el-table-column>
                    <el-table-column prop="riskLevel" label="风险等级" width="100">
                        <template slot-scope="scope">
                            <el-tag type="success" v-if="scope.row.riskLevel == 3" size="small">一般风险</el-tag>
                            <el-tag type="warning" v-if="scope.row.riskLevel == 2" size="small">较大风险</el-tag>
                            <el-tag type="danger" v-if="scope.row.riskLevel == 1" size="small">重大风险</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="workers" label="施工人员" width="150">
                        <template slot-scope="scope">
                            <span v-for="(item,index) in scope.row.workers">
                                {{((index != 0 ? ',' : '') + (item.empName || '-'))}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="teamLeader.groupName" label="班组" width="120"></el-table-column>
                    <el-table-column prop="machCmdsInfoList" label="所需设备" width="150">
                        <template slot-scope="scope">
                            <span v-for="(item,index) in scope.row.machCmdsInfoList">
                                {{((index != 0 ? ',' : '') + item)}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="planStartTime" label="工作开始时间" width="120"></el-table-column>
                    <el-table-column prop="planEndTime" label="工作结束时间" width="120"></el-table-column>
                    <el-table-column prop="creator.nickname" label="创建人" width="100"></el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="120"></el-table-column>
                    <el-table-column prop="auditStatus" label="状态" width="100">
                        <!-- <template slot-scope="scope">
                            <el-tag v-if="scope.row.auditStatus == 2" size="small">待审核</el-tag>
                            <el-tag v-if="scope.row.auditStatus == 1" size="small" type="success">已通过</el-tag>
                            <el-tag v-if="scope.row.auditStatus == 0" size="small" type="danger">已拒绝</el-tag>
                        </template> -->
                        <template slot-scope="scope">
                            <el-tag :type="
                                    scope.row.auditStatus == 0 ? 'primary' :
                                    scope.row.auditStatus == 1 ? 'primary' :
                                	scope.row.auditStatus == 2 ? 'success' :
                                	scope.row.auditStatus == 3 ? 'danger' :
                                	scope.row.auditStatus == 4 ? 'info' : 'info'
                                " >
                                {{
                                	scope.row.auditStatus == 0 ? '待审批' :
                                	scope.row.auditStatus == 1 ? '审批中' :
                                	scope.row.auditStatus == 2 ? '已通过' :
                                	scope.row.auditStatus == 3 ? '已拒绝' :
                                	scope.row.auditStatus == 4 ? '审批结束' : '已结束'
                                }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="旁站监护人员" align="center">
                        <!-- guardian1Id分包 guardian2Id总包 guardian3Id监理 guardian4Id业主-->
                        <el-table-column prop="guardian1" label="分包" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian1" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian1Id ? personNames(scope.row.guardian1Id) : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="guardian2" label="总包" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian2" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian2Id ? personNames(scope.row.guardian2Id) : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="guardian3" label="监理" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian3" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian3Id ? personNames(scope.row.guardian3Id) : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="guardian4" label="业主" align="center" width="150">
                            <template slot-scope="scope">
                                <!-- <div v-for="(item, index) in scope.row.guardian4" :key="index">
                                    {{((index!=0?',':'') + (item.empName || '-'))}}
                                </div> -->
                                {{
                                    scope.row.guardian4Id ? personNames(scope.row.guardian4Id) : ''
                                }}
                            </template>
                        </el-table-column>
                    </el-table-column>

                    <el-table-column label="操作" align="center" fixed="right" min-width="130" >
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="onView(scope.row)">查看</el-button>
                            <el-button type="text" size="small" style="margin-left: 0px;" @click="onEdit(scope.row)">编辑</el-button>
                            <!-- <el-button type="text" size="small" @click="onReview(scope.row)"
                                v-if="(scope.row.auditStatus == 0 || scope.row.auditStatus == 1) && scope.row.flag == true" >
                                审核
                            </el-button> -->
                            <!--
                            confirm	点击确认按钮时触发
                            cancel	点击取消按钮时触发
                            confirm-button-text	确认按钮文字
                            cancel-button-text	取消按钮文字
                            -->
                            <el-popconfirm
                                confirm-button-text='通过'
                                cancel-button-text='拒绝'
                                icon="el-icon-warning"
                                title="是否通过此工作计划审核!"
                                confirm-button-type="success"
                                cancel-button-type="danger"
                                @confirm="onReview(scope.row, 2)"
                                @cancel="onReview(scope.row, 3)"
                                popper-append-to-body
                            >
                                <!-- <div style="text-align: right; margin: 0">
                                    <el-button size="mini" type="text"  @click="onReview(scope.row, 2)">拒绝</el-button>
                                    <el-button type="primary" size="mini"  @click="onReview(scope.row, 3)">通过</el-button>
                                </div> -->
                                <el-button slot="reference" type="text" size="small"
                                    v-show="(scope.row.auditStatus == 0 || scope.row.auditStatus == 1) && scope.row.flag == true" >
                                    审核
                                </el-button>
                            </el-popconfirm>
                            <el-button type="text" size="small" @click="onGuardianship(scope.row)">修改旁站监护人员</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="clearfix">
                <div class="float-right">
                    <Page
                        v-if="totalCount"
                        style="margin: 20px 0;text-align: center;"
                        :current.sync="current"
                        :total="totalCount"
                        :page-size="pageSize"
                        show-elevator
                        show-total
                        show-sizer
                        @on-change="pageChange"
                        @on-page-size-change="pageSizeChange"
                    ></Page>
                </div>
            </div>
        </div>

        <Modal v-model="deleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(2)" type="info" size="small" plain>取消</el-button>
                <el-button @click="detele" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="updateModal" :title="popupType == 1 ? '添加工作计划' : '修改工作计划'" width="70%" min-width="520px" :mask-closable="false">
            <div class="item">
                <span class="tip">*</span>
                <span>计划名称:</span>
                <Input v-model="PlanName" type="text" placeholder="请输入计划名称内容" style="width: 300px" show-word-limit />
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>入场凭证:</span>
                <el-select v-model="rcpzIDValue" placeholder="请选择入场凭证" style="width:300px" @change="getQueryEntryerId" :filterable="true">
                    <el-option v-for="item in QueryEntryerIdList" :key="item.id" :label="item.id + (item.title ? (' / ' + item.title) : '')" :value="item.id">
                        <!-- {{item.id}}{{item.title ? (' / ' + item.title) : ''}} -->
                    </el-option>
                </el-select>
            </div>
            <div class="item" v-if="">
                <span class="tip">*</span>
                <span>施工人员:</span>
                <el-select v-model="sgryValue" placeholder="请选择入场凭证" style="width:300px" :disabled="rcpzIDValue ? false : true"
                    :filterable="true" multiple collapse-tags>
                    <el-option v-for="item in QueryWorkersList" :key="item.emp_id" :label="item.name" :value="item.emp_id"></el-option>
                </el-select>
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>计划开始:</span>
                <!-- <DatePicker type="date" v-model="AdmissionTime" placeholder="请选择计划开始" style="width: 300px" @on-change="getDate" ></DatePicker> -->
                <el-date-picker
                  v-model="AdmissionTime"
                  type="datetime"
                  placeholder="请选择计划开始"
                  style="width: 300px"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>计划结束:</span>
                <!-- <DatePicker type="date" v-model="DepartureTime" placeholder="请选择计划结束" style="width: 300px" @on-change="getDate1" ></DatePicker> -->
                <el-date-picker
                  v-model="DepartureTime"
                  type="datetime"
                  placeholder="请选择计划开始"
                  style="width: 300px"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>工作区域:</span>
                <Select v-model="gzqyValue" style="width:300px" placeholder="请选择工作区域" :filterable="true">
                    <Option v-for="item in QueryWorkAreaList" :value="item.id" :key="item.id" >{{ item.name }}</Option>
                </Select>
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>设备清单:</span>
                <el-select v-model="sbqdValue" placeholder="请选择设备清单" style="width:300px" :filterable="true" multiple collapse-tags>
                    <el-option v-for="item in QueryMachList" :key="item.machId" :label="item.machTypeName" :value="item.machId"></el-option>
                </el-select>
            </div>
            <div class="item">
                <span>风险等级:</span>
                <div class="radio">
                    <el-radio-group v-model="rgencyRadio">
                        <el-radio :label="3">一般风险</el-radio>
                        <el-radio :label="2">较大风险</el-radio>
                        <el-radio :label="1">重大风险</el-radio>
                    </el-radio-group>
                </div>
            </div>
            <div class="item">
                <!-- <span class="tip">*</span> -->
                <span>上传图片:</span>
                <el-upload style="width:300px" class="upload-demo" :on-preview="handlePreview" :on-remove="handleRemove" action=""
                    :before-remove="beforeRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList"
                    :http-request="httpRequest">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip"><!-- 上传文件不超过500kb --></div>
                </el-upload>
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>工作内容:</span>
                <Input v-model="checkDesc" type="textarea" placeholder="请输入工作内容" style="width: 300px" show-word-limit />
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>危险点*:</span>
                <Input v-model="DangerPoint" type="textarea" placeholder="请输入危险点" style="width: 300px" show-word-limit />
            </div>
            <div class="item">
                <span class="tip">*</span>
                <span>措施内容*:</span>
                <Input v-model="MeasuresContent" type="textarea" placeholder="请输入措施内容" style="width: 300px" show-word-limit />
            </div>

            <!-- <el-divider content-position="left">旁站监护人员</el-divider>

            <div class="item" style="width: 50%; min-width: 400px;">
                <span>分包:</span>
                <el-select v-model="ApiEmpItem.guardian1Id" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div class="item" style="width: 50%; min-width: 400px;">
                <span>总包:</span>
                <el-select v-model="ApiEmpItem.guardian2Id" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div class="item" style="width: 50%; min-width: 400px;">
                <span>监理:</span>
                <el-select v-model="ApiEmpItem.guardian3Id" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div class="item" style="width: 50%; min-width: 400px;">
                <span>业主:</span>
                <el-select v-model="ApiEmpItem.guardian4Id" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div> -->

            <div slot="footer">
                <el-button @click="cancel(1)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submitAll" type="primary" size="small" plain v-preventReClick="2000" :loading="ModalLoading">确定</el-button>
            </div>
        </Modal>

        <!-- Table -->
        <el-dialog title="工作计划审核" :visible.sync="dialogTableVisible" width="80%" top="10vh">
          <div class="bottom">
              <div class="table">
                  <el-table :data="gridData.approvalRecords" :height="tableHeight" :stripe="true" style="width: 100%">
                        <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                        <el-table-column prop="applicantUser.nickname" label="申请人" align="center" >
                            <template slot-scope="scope">
                                {{ gridData.creator ? gridData.creator.nickname : '' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="approvalUser.nickname" label="审批人" align="center" ></el-table-column>
                        <el-table-column prop="approvalTime" label="审批时间" align="center" ></el-table-column>
                        <el-table-column prop="approvalResult" label="状态"  align="center">
                            <template slot-scope="scope">
                                <!--  0 ? '待审批' 1 ? '审批中' 2 ? '已通过' 3 ? '已拒绝' 4 ? '审批结束' -->
                                <el-tag :type="
                                        scope.row.approvalResult == 0 ? 'primary' :
                                        scope.row.approvalResult == 1 ? 'primary' :
                                        scope.row.approvalResult == 2 ? 'success' :
                                        scope.row.approvalResult == 3 ? 'danger' :
                                        scope.row.approvalResult == 4 ? 'info' : 'info'
                                    " >
                                    {{
                                        scope.row.approvalResult == 0 ? '待审批' :
                                        scope.row.approvalResult == 1 ? '审批中' :
                                        scope.row.approvalResult == 2 ? '已通过' :
                                        scope.row.approvalResult == 3 ? '已拒绝' :
                                        scope.row.approvalResult == 4 ? '审批结束' : '已结束'
                                    }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <!--  0 ? '待审批' 1 ? '审批中' 2 ? '已通过' 3 ? '已拒绝' 4 ? '审批结束' flag：true 有 flase 没有 -->
                        <!-- <el-table-column label="操作" align="center" fixed="right" width="130">
                            <template slot-scope="scope">
                                    <div v-if="(scope.row.approvalResult == 1 || scope.row.approvalResult == 0)
                                        && scope.row.flag == true && scope.row.approvalUser.id == userId">
                                        <el-button type="text" size="small" @click="onReview(gridData)">审核</el-button>
                                    </div>
                            </template>
                        </el-table-column> -->
                  </el-table>
              </div>
          </div>
        </el-dialog>

        <Modal v-model="guardianshipModal" title="旁站监护人员" width="50%" :mask-closable="false">
            <div class="item" style="width: 100%;">
                <!-- <span class="tip">*</span> -->
                <span>分包:</span>
                <el-select v-model="ApiEmpItem.guardian1Id" :disabled="guardian1Type" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div class="item" style="width: 100%;">
                <!-- <span class="tip">*</span> -->
                <span>总包:</span>
                <el-select v-model="ApiEmpItem.guardian2Id" :disabled="guardian2Type" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div class="item" style="width: 100%;">
                <!-- <span class="tip">*</span> -->
                <span>监理:</span>
                <el-select v-model="ApiEmpItem.guardian3Id" :disabled="guardian3Type" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div class="item" style="width: 100%;">
                <!-- <span class="tip">*</span> -->
                <span>业主:</span>
                <el-select v-model="ApiEmpItem.guardian4Id" :disabled="guardian4Type" placeholder="请选择" multiple filterable style="width: 90%;">
                    <el-option v-for="item in ApiEmpList" :key="item.empId" :label="item.empName" :value="item.empId"></el-option>
                </el-select>
            </div>
            <div slot="footer">
                <el-button @click="guardianshipModal = false" type="info" size="small" plain>取消</el-button>
                <el-button @click="onGuardian" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
    </div>
</template>

<script>

import {
    getEmpRewardList,
    getEmpRewardAdd,
    getEmpRewardDel,
    getAllPersonnelList,
    getSelectValue
} from "@/api/api.js";
import {
    apiWorkPlanWorkPageList,
    apiWorkPlanWorkSaveWorkPlan,
    apiWorkPlanQueryEntryerId,
    apiWorkPlanQueryWorkers,
    apiWorkPlanQueryWorkArea,
    appApplyWorkQueryMach,
    appDocumentManageFileUpload,
    appApplyWorkEntryReview,
    appWorkPlanDetail,
    appWorkPlanEdit,
    apiApplyWorkQueryReviewList,
    apiWorkPlanWorkList,
    getApiEmpList
} from "@/api/apifox.js";
export default {
    data() {
        return {
            fileList: [],
            current: 1,
            pageSize: 10,
            pageNum: 1,
            totalCount: "",
            projectId: "",
            keyword: "",
            list: [],
            updateModal: false,
            popupType: 1, // 1添加 2修改
            removeId: "",
            deleteModal: false,
            btnList: [],
            deptName: "",
            startDate: "",
            endDate: "",
            value: [],
            tableHeight: window.innerHeight - 355,

            PlanName: '', // 计划名称
            rcpzIDValue: '', // 入场凭证id
            sgryValue: '', // 施工人员选择的值
            gzqyValue: '', // 工作区域选择的值
            sbqdValue: '', // 设备清单选择的值
            fileImg: '', // 上传的图片
            checkDesc: '', // 工作内容内容
            DangerPoint: '', // 危险点
            MeasuresContent: '', // 措施内容
            rgencyRadio: 3, // 风险等级：1、一级：重大风险 2、二级：较大风险 3、三级: 一般风险
            AdmissionTime: '', // 计划开始
            DepartureTime: '', // 计划结束

            QueryEntryerIdList: [], // 入场凭证ID
            QueryWorkersList: [], // 施工人员
            QueryWorkAreaList: [], // 工作区域
            QueryMachList: [], // 设备清单

            formData: {
              fileName: '', // 附件名称
              fileSize: '', // 附件大小
              fileType: '', // 附件类型
              fileUrl: '',  // 附件路径
            },

            DetailItem: '',
            dialogTableVisible: false, // 列表弹出层
            gridData: [], // 弹出层列表
            userId: null, // 用户id

            ModalLoading: false,

            guardianshipModal: false, // 旁站监护人员弹出层
            ApiEmpList: [], // 查询所有人员（不分页）
            ApiEmpItem: {
                id: null, // id
                guardian1Id: [], // 分包
                guardian2Id: [], // 总包
                guardian3Id: [], // 监理
                guardian4Id: [], // 业主
            },
            guardian1Type: true,
            guardian2Type: true,
            guardian3Type: true,
            guardian4Type: true,

            visible: false,
        };
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        }
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.projectId = val.deptId;
                this.deptName = val.name;
                this.pageNum = 1;
                this.current = 1;
                this.keyword = "";
                this.value = [];
                this.getAllList();
                this.getEmpList();
            }
        }
    },

    created() {

    },
    mounted() {
        this.projectId = this.$store.state.porjectObject.deptId;
        this.deptName = this.$store.state.porjectObject.name;
        this.userId = localStorage.getItem('userId')
        this.visible = false;
        this.getAllList();
        this.getEmpList();
        this.btnList = JSON.parse(localStorage.getItem("arr"));
    },
    methods: {
        personNames(idStr) {
            // 容错处理：如果传入的idStr为空或非字符串，直接返回空数组
            if (!idStr || typeof idStr !== 'string') {
                return [];
            }

            // 拆分ID字符串为数组，并过滤空字符串（避免因输入类似 '11,,34' 导致的空ID）
            const ids = idStr.split(',').filter(id => id.trim() != '');

            // 遍历ID数组查询名称
            const nameList = ids.map(id => {
                // 若ApiEmpList不存在，直接返回未知
                if (!this.ApiEmpList || !Array.isArray(this.ApiEmpList)) {
                  return '';
                }
                // 查找对应人员（trim处理id，避免前后空格导致匹配失败）
                const person = this.ApiEmpList.find(p => p.empId == id.trim());
                return person ? person.empName : '';
            });

            return nameList.join(',');
        },
        onReview(row, val) {
            console.log(row, val);
            // return
            this.getWorkEntryReview(row, val);
            /* this.$confirm('是否通过此工作计划审核', '提示', {
                confirmButtonText: '通过',
                cancelButtonText: '拒绝',
                type: 'warning',
                center: true
            }).then(() => {
                this.getWorkEntryReview(row, 2);
            }).catch(() => {
                this.getWorkEntryReview(row, 3);
            }); */
        },
        onView(row) {
            this.gridData = [];
            this.gridData = row;
            let approvalRecords = [];

            row.approvalRecords.forEach((item, index) => {
                /* 0: '待审批' / 1: '审批中' / 2: '已通过' / 3: '已拒绝' / 4: '审批结束' / */
                if (item.approvalResult == 2 || item.approvalResult == 3 || item.approvalResult == 4) {
                    approvalRecords.push(item);
                }
            });
            this.gridData.approvalRecords = approvalRecords;
            this.dialogTableVisible = true;
            /* apiApplyWorkQueryReviewList({
                id: row.entryPermitId,
                isReview: 2 // (1:入场,2:计划)
            }).then(res => {
                if (res.code == 200) {
                    this.gridData = res.data;
                    this.dialogTableVisible = true;
                    // this.totalCount = res.data.total;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            }); */
        },
        getWorkEntryReview(row, e) {
            if(this.visible == true) {
                return;
            }
            this.visible = true;
            let currentApprovalRecord;
            for (var index = 0; index < row.approvalRecords.length; index++) {
            	var element = row.approvalRecords[index];
            	if(element.approverId == this.userId){
            		currentApprovalRecord = element
            	}
            }
            appApplyWorkEntryReview({
            	id: currentApprovalRecord.id,
            	approvalResult: e
            }).then(res => {
                if (res.code == 200) {
                    this.dialogTableVisible = false;
                    this.getAllList();
                    this.$message({
                        type: 'success',
                        message: '审核操作成功!'
                    });
                } else {
                    this.$Message.warning(res.msg);
                }
                this.visible = false;
            }).catch(error => {
                console.log(error);
                this.visible = false;
            });
        },
        onEdit(row) {
            this.PlanName = ''; // 计划名称
            this.rcpzIDValue = ''; // 入场凭证id
            this.sgryValue = ''; // 施工人员选择的值
            this.gzqyValue = ''; // 工作区域选择的值
            this.sbqdValue = ''; // 设备清单选择的值
            this.fileImg = ''; // 上传的图片
            this.checkDesc = ''; // 工作内容内容
            this.DangerPoint = ''; // 危险点
            this.MeasuresContent = ''; // 措施内容
            this.rgencyRadio = 3; // 风险等级：1、一级：重大风险 2、二级：较大风险 3、this.三级 = 一般风险
            this.AdmissionTime = ''; // 计划开始
            this.DepartureTime = ''; // 计划结束
            this.QueryWorkersList = []; // 施工人员
            this.DetailItem = '';
            this.fileList = [];
            this.ApiEmpItem = {
                id: null, // id
                guardian1Id: [], // 分包
                guardian2Id: [], // 总包
                guardian3Id: [], // 监理
                guardian4Id: [], // 业主
            }


            appWorkPlanDetail({
                id: row.id,
            }).then(res => {
                console.log('appWorkPlanDetail', res)
                if (res.code == 200) {
                    this.getQueryEntryerId(res.data.entryPermitId);
                    this.DetailItem = res.data;
                    console.log('DetailItem', this.DetailItem)

                    this.PlanName = this.DetailItem.planName; // 计划名称
                    this.rcpzIDValue = this.DetailItem.entryPermitId; // 入场凭证id
                    this.sgryValue = this.DetailItem.constructionWorkers ? this.DetailItem.constructionWorkers.split(',').map(Number) : ''; // 施工人员选择的值
                    this.gzqyValue = this.DetailItem.workAreaId; // 工作区域选择的值
                    this.sbqdValue = this.DetailItem.machCmdsInfoList ? this.DetailItem.machCmdsInfoList.map(Number) : ''; // 设备清单选择的值
                    this.fileImg = this.DetailItem.uploadedFilePath; // 上传的图片
                    this.checkDesc = this.DetailItem.workContent; // 工作内容内容
                    this.DangerPoint = this.DetailItem.risk; // 危险点
                    this.MeasuresContent = this.DetailItem.measures; // 措施内容
                    this.rgencyRadio = Number(this.DetailItem.riskLevel); // 风险等级：1、一级：重大风险 2、二级：较大风险 3、this.三级 = 一般风险
                    this.AdmissionTime = this.DetailItem.planStartTime; // 计划开始
                    this.DepartureTime = this.DetailItem.planEndTime; // 计划结束

                    this.ApiEmpItem = {
                        id: this.DetailItem.id, // id
                        guardian1Id: this.DetailItem.guardian1Id ? this.DetailItem.guardian1Id.split(',').map(num => parseInt(num, 10)) : [], // 分包
                        guardian2Id: this.DetailItem.guardian2Id ? this.DetailItem.guardian2Id.split(',').map(num => parseInt(num, 10)) : [], // 总包
                        guardian3Id: this.DetailItem.guardian3Id ? this.DetailItem.guardian3Id.split(',').map(num => parseInt(num, 10)) : [], // 监理
                        guardian4Id: this.DetailItem.guardian4Id ? this.DetailItem.guardian4Id.split(',').map(num => parseInt(num, 10)) : [], // 业主
                    }


                    if(this.fileImg) {
                        this.fileList.push({
                            url: this.fileImg,
                            name: '文件名称',
                        });
                    }

                    this.popupType = 2
                    this.updateModal = true;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
        },
        updateRow() {
            console.log('1111111')
            this.PlanName = ''; // 计划名称
            this.rcpzIDValue = ''; // 入场凭证id
            this.sgryValue = ''; // 施工人员选择的值
            this.gzqyValue = ''; // 工作区域选择的值
            this.sbqdValue = ''; // 设备清单选择的值
            this.fileImg = ''; // 上传的图片
            this.checkDesc = ''; // 工作内容内容
            this.DangerPoint = ''; // 危险点
            this.MeasuresContent = ''; // 措施内容
            this.rgencyRadio = 3; // 风险等级：1、一级：重大风险 2、二级：较大风险 3、this.三级 = 一般风险
            this.AdmissionTime = ''; // 计划开始
            this.DepartureTime = ''; // 计划结束
            this.QueryWorkersList = []; // 施工人员
            this.fileList = [];

            this.ApiEmpItem = {
                id: null, // id
                guardian1Id: [], // 分包
                guardian2Id: [], // 总包
                guardian3Id: [], // 监理
                guardian4Id: [], // 业主
            }

            this.popupType = 1
            this.updateModal = true;
            console.log('22222222', this.updateModal)
        },
        //获取所有人员
        getEmpList() {
            let params = {
                deptId: this.projectId
            };

            /* apiWorkPlanWorkList().then(res => {
                if (res.code == 200) {

                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            }); */
            getApiEmpList(params).then(res => {
                console.log('查询所有人员（不分页）：', res);
                if (res.code == 200) {
                    this.ApiEmpList = res.data.list
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });

            apiWorkPlanQueryEntryerId().then(res => {
                if (res.code == 200) {
                    this.QueryEntryerIdList = res.data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
            apiWorkPlanQueryWorkArea(params).then(res => {
                if (res.code == 200) {
                    this.QueryWorkAreaList = res.data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
            appApplyWorkQueryMach(params).then(res => {
                if (res.code == 200) {
                    this.QueryMachList = res.data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
        },
        getAllList() {
            let params = {
                pageSize: this.pageSize, // 分页大小
                pageNum: this.pageNum, // 分页页码
                keyword: this.keyword, //
                projectId: this.projectId, //
                startTiem: this.startDate, // 开始时间
                endTiem: this.endDate, // 结柬时间
                createUserId: '', // 创建人Id
                isExit: '', // 是否离场 1到场 2离场
                startTimeBegin: this.startDate,
                startTimeEnd: this.endDate,
            };
            apiWorkPlanWorkPageList(params).then(res => {
                if (res.code == 200) {
                    this.list = res.data.list;
                    this.totalCount = res.data.total;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
            /* getEmpRewardList(params)
                .then(res => {
                    if (res.code == 200) {
                        this.list = res.data.list;
                        this.totalCount = res.data.total;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                }); */
        },
        getTime(value) {
            if (value === null) {
                console.log("点击了清空按钮，日期已清空");
                this.startDate = '';
                this.endDate = '';
                // 处理清空后的逻辑
            } else {
                console.log("选择了日期：", value);
                this.startDate = value[0];
                this.endDate = value[1];
            }
            // this.pageNum = 1;
            // this.current = 1;
            // this.getAllList();
        },
        // onSearch() {
        //     this.pageNum = 1;
        //     this.current = 1;
        //     this.getAllList();
        // },

        onSerch() {
            this.pageNum = 1;
            this.current = 1;
            this.getAllList();
        },
        onReset(){
            this.value = []
            this.startDate = null
            this.endDate = null
            this.keyword = null
            this.pageNum = 1;
            this.current = 1;
            this.visible = false;
            this.getAllList();
        },
        pageChange(index) {
            this.pageNum = index;
            this.getAllList();
        },
        pageSizeChange(index) {
            this.pageSize = index;
            this.getAllList();
        },

        getQueryEntryerId(index) {
            console.log(this.rcpzIDValue)
            this.sgryValue = '';
            this.rcpzIDValue = index;
            console.log(this.rcpzIDValue, index)
            apiWorkPlanQueryWorkers({
               id: this.rcpzIDValue
            }).then(res => {
                if (res.code == 200) {
                    this.QueryWorkersList = res.data;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error => {
                console.log(error);
            });
        },
        getDate(value) {
            this.AdmissionTime = value;
        },
        getDate1(value) {
            this.DepartureTime = value;
        },
        submitAll() {
            if(this.projectId == '') {
                this.$Message.warning('项目错误-项目ID未获取到');
            	return
            }
            if(this.PlanName == '') {
                this.$Message.warning('请输入计划名称');
            	return
            }
            if(this.rcpzIDValue == '' || this.rcpzIDValue == undefined) {
                this.$Message.warning('请选择入场凭证');
            	return
            }
            if(this.sgryValue == '' || this.sgryValue == undefined) {
                this.$Message.warning('请选择施工人员');
            	return
            }
            if(this.gzqyValue == '' || this.gzqyValue == undefined) {
                this.$Message.warning('请选择工作区域');
            	return
            }
            if(this.sbqdValue == '' || this.sbqdValue.length == 0) {
                this.$Message.warning('请选择设备清单');
            	return
            }
            // if(this.fileImg == '') {
            //     this.$Message.warning('请选择上传文件');
            // 	return
            // }
            if(this.checkDesc == '') {
                this.$Message.warning('请输入工作内容');
            	return
            }
            if(this.AdmissionTime == '') {
                this.$Message.warning('请选择计划开始时间');
            	return
            }
            if(this.DepartureTime == '') {
                this.$Message.warning('请选择计划结束时间');
            	return
            }

            this.ModalLoading = true;
            if(this.popupType == 1) {
                let param = {
                	deptId: this.projectId.toString(), // 项目Id
                	planName: this.PlanName, // 计划名称
                	entryPermitId: this.rcpzIDValue, // 入场凭证id
                	constructionPersonnelIds: this.sgryValue, // 施工人员选择的值
                	workAreaId: this.gzqyValue, // 工作区域选择的值
                	equipmentIds: this.sbqdValue ? this.sbqdValue : [], // 设备清单选择的值
                	uploadedFilePath: this.fileImg, // 上传的图片
                	workContent: this.checkDesc, // 工作内容内容
                    risk: this.DangerPoint, // 危险点
                    measures: this.MeasuresContent, // 措施内容
                	riskLevel: Number(this.rgencyRadio), // 风险等级：1、一级：重大风险 2、二级：较大风险 3、三级: 一般风险
                	planStartTime: this.AdmissionTime, // 计划开始
                	planEndTime: this.DepartureTime, // 计划结束

                    guardian1Id: this.ApiEmpItem.guardian1Id, // 分包
                    guardian2Id: this.ApiEmpItem.guardian2Id, // 总包
                    guardian3Id: this.ApiEmpItem.guardian3Id, // 监理
                    guardian4Id: this.ApiEmpItem.guardian4Id, // 业主
                };
                console.log("param: ", param);
                // this.updateModal = false;
                // return
                apiWorkPlanWorkSaveWorkPlan(param).then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.updateModal = false;
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                    this.ModalLoading = false;
                }).catch(error => {
                    console.log(error);
                    this.ModalLoading = false;
                });
            } else {
                let param = {
                    id: this.DetailItem.id, // id
                	deptId: this.projectId.toString(), // 项目Id
                	planName: this.PlanName, // 计划名称
                	entryPermitId: this.rcpzIDValue, // 入场凭证id
                	constructionPersonnelIds: this.sgryValue, // 施工人员选择的值
                	workAreaId: this.gzqyValue, // 工作区域选择的值
                	equipmentIds: this.sbqdValue ? this.sbqdValue : [], // 设备清单选择的值
                	uploadedFilePath: this.fileImg, // 上传的图片
                	workContent: this.checkDesc, // 工作内容内容
                    risk: this.DangerPoint, // 危险点
                    measures: this.MeasuresContent, // 措施内容
                	riskLevel: Number(this.rgencyRadio), // 风险等级：1、一级：重大风险 2、二级：较大风险 3、三级: 一般风险
                	planStartTime: this.AdmissionTime, // 计划开始
                	planEndTime: this.DepartureTime, // 计划结束

                    guardian1Id: this.ApiEmpItem.guardian1Id, // 分包
                    guardian2Id: this.ApiEmpItem.guardian2Id, // 总包
                    guardian3Id: this.ApiEmpItem.guardian3Id, // 监理
                    guardian4Id: this.ApiEmpItem.guardian4Id, // 业主
                };
                console.log("param: ", param);
                // this.updateModal = false;
                // return
                appWorkPlanEdit(param).then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.updateModal = false;
                        this.getAllList();
                    } else {
                        this.$Message.warning(res.msg);
                    }
                    this.ModalLoading = false;
                }).catch(error => {
                    console.log(error);
                    this.ModalLoading = false;
                });
            }

        },

        onGuardianship(row) {
            this.guardian4Type = true;
            this.guardian3Type = true;
            this.guardian2Type = true;
            this.guardian1Type = true;

            this.ApiEmpItem = {
                id: null, // id
                guardian1Id: [], // 分包
                guardian2Id: [], // 总包
                guardian3Id: [], // 监理
                guardian4Id: [], // 业主
            }
            this.ApiEmpItem = {
                id: row.id, // id
                guardian1Id: row.guardian1Id ? row.guardian1Id.split(',').map(num => parseInt(num, 10)) : [], // 分包
                guardian2Id: row.guardian2Id ? row.guardian2Id.split(',').map(num => parseInt(num, 10)) : [], // 总包
                guardian3Id: row.guardian3Id ? row.guardian3Id.split(',').map(num => parseInt(num, 10)) : [], // 监理
                guardian4Id: row.guardian4Id ? row.guardian4Id.split(',').map(num => parseInt(num, 10)) : [], // 业主
            }

            /*
                分包: guardian1Type
                总包: guardian2Type
                监理: guardian3Type
                业主: guardian4Type
            */
            for (var index = 0; index < row.approvalRecords.length; index++) {
                if(row.approvalRecords[index].approverId == this.userId) {
                    if(row.approvalRecords[index].approvalUser.userType == 0) {
                        /* 业主人员 */
                        this.guardian4Type = false;
                    } else if(row.approvalRecords[index].approvalUser.userType == 1) {
                        /* 监理人员 */
                        this.guardian3Type = false;
                    } else if(row.approvalRecords[index].approvalUser.userType == 2) {
                        /* 总包人员 */
                        this.guardian2Type = false;
                    } else if(row.approvalRecords[index].approvalUser.userType == 3) {
                        /* 分包人员 */
                        this.guardian1Type = false;
                    } else {
                        /* userType：4普通人员 和其它 */
                        this.guardian4Type = true;
                        this.guardian3Type = true;
                        this.guardian2Type = true;
                        this.guardian1Type = true;
                    }
                }
            }

            console.log('ApiEmpItem: ', this.ApiEmpItem);
            this.guardianshipModal = true;
        },
        onGuardian() {
            let param = {
                id: this.ApiEmpItem.id, // id
                guardian1Id: this.ApiEmpItem.guardian1Id, // 分包
                guardian2Id: this.ApiEmpItem.guardian2Id, // 总包
                guardian3Id: this.ApiEmpItem.guardian3Id, // 监理
                guardian4Id: this.ApiEmpItem.guardian4Id, // 业主
            };
            appWorkPlanEdit(param).then(res => {
                if (res.code == 200) {
                    this.$Message.success("操作成功");
                    this.guardianshipModal = false;
                    this.getAllList();
                } else {
                    this.$Message.warning(res.msg);
                }
                this.ModalLoading = false;
            }).catch(error => {
                console.log(error);
                this.ModalLoading = false;
            });
        },

        remove(index, rows) {
            this.removeId = rows[index].id;
            this.deleteModal = true;
        },
        detele() {
            getEmpRewardDel(this.removeId)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getAllList();
                        this.deleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },

        cancel(type) {
            if (type == 1) {
                this.updateModal = false;
            } else if (type == 2) {
                this.deleteModal = false;
            }
        },

        //实现图片上传功能
        httpRequest(item) {
            console.log('0', item.file.name);
            var formData = new FormData()
            formData.append('file', item.file)
            appDocumentManageFileUpload(formData).then(res => {
                console.log('上传结果', res);
                this.fileImg = res.data.path;
                this.formData.fileName = res.data.name; // 附件名称
                this.formData.fileSize = res.data.size; // 附件大小
                this.formData.fileType = res.data.fileType; // 附件类型
                this.formData.fileUrl = res.data.path; // 附件路径
                this.$Message.success("上传成功");

            }).catch((err) => {
                console.log(error);
            })
        },
        handleRemove(file, fileList) {
            console.log('1', file, fileList);
            this.formData.fileName = ''; // 附件名称
            this.formData.fileSize = ''; // 附件大小
            this.formData.fileType = ''; // 附件类型
            this.formData.fileUrl = ''; // 附件路径
        },
        handlePreview(file) {
            console.log('2', file);
        },
        handleExceed(files, fileList) {
            console.log('3', files, fileList);
            this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            console.log('4', file, fileList);
            return this.$confirm(`确定移除 ${file.name}？`);
        },
    },
};
</script>

<style scoped lang="less">
// @import "./../../assets/style/emp_common.less";
@import "./../../assets/style/themeBase.less";
.empReward {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background: #f5f5f5;
    .top {
        width: 100%;
        height: 72px;
        background: #fff;
        border-radius: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .search {
            width: auto;
            margin-left: 20px;
            padding-top: 20px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .list {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                padding-bottom: 20px;
                margin-right: 20px;
                span {
                    width: 70px;
                }
            }
        }
        .down {
            width: auto;
            margin-right: 20px;
        }
    }
    .bottom {
        width: 100%;
        padding: 20px;
        margin-top: 10px;
        box-sizing: border-box;
        height: calc(100% - 82px);
        background: #fff;
        border-radius: 10px;
        .down {
            width: 98%;
            margin: 0 auto;
            margin-top: 20px;
        }
        .msg {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            .list {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                margin-right: 24px;
                p {
                    margin-right: 10px;
                    font-size: 16px;
                    color: #000;
                    &:nth-child(2) {
                        color: red;
                    }
                }
            }
        }
        .updateCorp {
            cursor: pointer;
            margin-left: 5px;
            padding: 2px 4px;
            font-size: 12px;
            font-weight: 400;
            line-height: 1;
            color: #ffffff;
            border-radius: 3px;
            background-color: var(--themeColor);
        }
    }
}
.item {
    width: 400px;
    display: flex;
    margin: 0 auto;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    position: relative;
    margin-bottom: 20px;
    padding-left: 16px;
    box-sizing: border-box;
    .radio {
        width: 300px;
        display: flex;
        justify-content: center;
    }
    .tip {
        position: absolute;
        top:8px;
        left:0;
        color: red;
        font-size: 16px;
    }
}
// /deep/.ivu-icon-ios-close{
//     color: #fff;
//     &:hover{
//         color: #fff;
//     }
// }



/deep/.ivu-input-group{
    border-radius:20px;
    }
    /deep/.ivu-input-group .ivu-input{
        border-radius: 20px 0 0 20px;
        border-color:#EBF2F8;
        background:#EBF2F8;
    }
    /deep/.ivu-input-group-append{
        border-radius: 0 20px 20px 0;
    }
    /deep/.el-tag.el-tag--success{
        background-color: #E7F8F2;
        border-color: #28D79C;
        color: #3FCF77;
    }
    /deep/.el-tag{
        border-radius: 2px;
    }
    /deep/.ivu-select-selection{
        border-radius: 2px;
    }
    /deep/.el-tag.el-tag--info{
    background-color:rgba(255, 72, 72, 0.1);
    border-radius:2px;
    border-color:#FF4848;
    color:#FF4848;
}

/deep/.ivu-modal-body {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}
</style>
<style lang="scss">
.el-popconfirm__main {
  margin: 23px 24px 17px 24px;
  font-size: 14px;
  font-family: MicrosoftYaHei;
  color: #333333;
}
.el-popconfirm__action {
  margin-bottom: 24px;
  padding-bottom: 24px;
  // 交换 确定 和 取消 按钮的位置
  .el-button:nth-child(1) {
    float: right;
    margin-right: 23%;
    // width: 72px;
    // height: 32px;
    // background: #055fe7;
    // border-radius: 4px;
    // font-size: 14px;
    // font-family: MicrosoftYaHei;
    // color: #ffffff;
  }
  .el-button:nth-child(2) {
    float: left;
    margin-left: 23%;
    // width: 72px;
    // height: 32px;
    // background: #ffffff;
    // border-radius: 4px;
    // border: 1px solid #aeb5c2;
    // font-size: 14px;
    // font-family: MicrosoftYaHei;
    // color: #2e3846;
  }
}

.el-table {
        ::-webkit-scrollbar {
            height: 10px;
            /* 横向滚动条 高度 */
        }

        ::-webkit-scrollbar-thumb {
            // 滚动条上的滚动滑块
            // background: #000 !important;
            height: 10px;
        }
    }
</style>
